#pragma once
#include <iostream>
#include <vector>
#include <semaphore.h>
#include <pthread.h>


const static int defaultcap = 5;

template<class T>
class RingQueue
{
private:
    //申请信号量(P操作)
    void P(sem_t &sem)
    {
        sem_wait(&sem);
    }

    //释放信号量(V操作)
    void V(sem_t &sem)
    {
        sem_post(&sem);
    }

    //上锁
    void Lock(pthread_mutex_t &mutex)
    {
        pthread_mutex_lock(&mutex);
    }

    //解锁
    void Unlock(pthread_mutex_t &mutex)
    {
        pthread_mutex_unlock(&mutex);
    }

public:
    RingQueue(int cap = defaultcap)
    :ringqueue_(cap),cap_(cap),c_step_(0),p_step_(0)
    {
        //初始化信号量
        sem_init(&cdata_sem_, 0,0);
        sem_init(&pspace_sem_, 0,cap);

        //初始化锁
        pthread_mutex_init(&c_mutex_,nullptr);
        pthread_mutex_init(&p_mutex_,nullptr);
    }

    //push操作
    void Push(const T &in)
    {
        //多线程 先申请信号量，再上锁  sem_wait是原子性的
        P(pspace_sem_);
        Lock(p_mutex_);

        ringqueue_[p_step_]=in;
        p_step_++;
        p_step_%=cap_;//%=来实现环形

        Unlock(p_mutex_);
        V(cdata_sem_);
    }


    //pop
    void Pop(T *out)      
    {
        P(cdata_sem_);
        Lock(c_mutex_); 

        *out = ringqueue_[c_step_];
        // 位置后移，维持环形特性
        c_step_++;
        c_step_ %= cap_;

        Unlock(c_mutex_); 
        V(pspace_sem_);
    }

    ~RingQueue()
    {
        sem_destroy(&cdata_sem_);
        sem_destroy(&pspace_sem_);

        pthread_mutex_destroy(&c_mutex_);
        pthread_mutex_destroy(&p_mutex_);
    }



private:
    std::vector<T> ringqueue_;  //基于vector创建环形数组

    int cap_;

    //创建c 和 p 两个下表
    size_t c_step_;
    size_t p_step_;

    sem_t cdata_sem_; //消费者关注的资源
    sem_t pspace_sem_; //生产者关注的资源

    //创建c p 两把锁
    pthread_mutex_t c_mutex_;
    pthread_mutex_t p_mutex_;


};